﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.Management;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using MediatR;
using MedicalPCTerminal.Write.API.Appcation.Commands.Management;

namespace MedicalPCTerminal.Write.API.Appcation.CommandHandlers.Management
{
    /// <summary>
    /// 处理添加健康报告命令
    /// </summary>
    public class AddReportsCommandHandler : IRequestHandler<AddReportsCommand, APIResult<object>>
    {
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// sqlsugar
        /// </summary>
        private readonly SqlSugarContext sqlSugar;
        private readonly ILogger<AddReportsCommandHandler> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="sqlSugar">sqlsugar</param>
        public AddReportsCommandHandler(IMapper mapper, SqlSugarContext sqlSugar, ILogger<AddReportsCommandHandler> logger)
        {
            this.mapper = mapper;
            this.sqlSugar = sqlSugar;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<object>> Handle(AddReportsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<object> result = new APIResult<object>();
                var entity = mapper.Map<Reports>(request);
                entity.Publisher = 0;
                entity.CreateTime = DateTime.Now;
                entity.Status = "未发布";
                var i = sqlSugar.db.Insertable<Reports>(entity).ExecuteCommand();
                if (i > 0)
                {
                    result.Code = APIEnum.添加成功;
                    result.Msg = APIEnum.添加成功.ToString();
                    result.data = entity;
                }
                else
                {
                    result.Code = APIEnum.添加失败;
                    result.Msg = APIEnum.添加失败.ToString();
                    result.data = entity;
                }
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("新增失败" + ex.Message);
                throw;
            }

        }
    }
}
